# -*-coding:utf-8-*-

import pyrestful.rest
from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete
from pymongo.collection import ReturnDocument
from utils.auth import authenticated
import time, json
from datetime import datetime, timedelta
import handlers.base


class VendorsHandler(handlers.base.BaseHandler):
    def __init__(self, application, request, **kwargs):
        super(VendorsHandler, self).__init__(application, request, **kwargs)
        self.vendors_dao = self.settings['daos']['vendors']
        self.users_dao = self.settings['daos']['users']

    def check_permissions(self, permissions):
        return True

    @authenticated
    @get(_path='/platform/api/vendors', _produces=mediatypes.APPLICATION_JSON)
    def get_vendor_list(self):
        result = self.vendors_dao.get_vendor_list(self.user_id)
        self.response_success(result)

    @authenticated
    @post(_path='/platform/api/vendors', _produces=mediatypes.APPLICATION_JSON)
    def create_vendor(self):
        request = json.loads(self.request.body)
        phone = request['phone']
        user = self.users_dao.get_user_by_phone_no(self.app, phone)
        if user is None:
            self.response_error('user_not_exists')
            return
        vendor_id = user.id_str
        if self.vendors_dao.get_vendor_by_id(vendor_id) is not None:
            self.response_error('user_already_exists')
            return
        request['vendor_id'] = vendor_id
        result = self.vendors_dao.create_vendor(self.user_id, request)
        self.users_dao.update_user_with_vendor_id(self.app, result['vendor_id'])
        self.response_success(result)

    @authenticated
    @get(_path='/platform/api/vendors/{vid}', _types=[str], _produces=mediatypes.APPLICATION_JSON)
    def get_vendor(self, vid):
        result = self.vendors_dao.get_vendor(self.user_id, vid)
        self.response_success(result)

    @authenticated
    @put(_path='/platform/api/vendors/{vid}', _types=[str], _produces=mediatypes.APPLICATION_JSON)
    def update_vendor(self, vid):
        request = json.loads(self.request.body)
        result = self.vendors_dao.update_vendor(self.user_id, vid, request)
        self.response_success(result)

    @authenticated
    @delete(_path='/platform/api/vendors/{vid}', _types=[str], _produces=mediatypes.APPLICATION_JSON)
    def delete_vendor(self, vid):
        result = self.vendors_dao.delete_vendor(self.user_id, vid)
        self.response_success(result)
  